/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.modules.autocode.global.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.app.VelocityEngine;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

import cn.com.ksplatform.base.BaseController;
import cn.com.ksplatform.base.adapter.IRequestParamAdapter;
import cn.com.ksplatform.base.adapter.RuleNotFondException;
import cn.com.ksplatform.base.dao.IBaseJdbcDAO;
import cn.com.ksplatform.base.hibernate.dialect.IDialect;
import cn.com.ksplatform.base.page.PageInfoModel;
import cn.com.ksplatform.common.logger.Log;
import cn.com.ksplatform.modules.autocode.dto.Column;
import cn.com.ksplatform.modules.autocode.dto.ColumnArray;
import cn.com.ksplatform.modules.autocode.manager.model.Sence;
import cn.com.ksplatform.modules.autocode.util.SenceUtil;

/**
 * ClassName:Adapter_0_go.java <br/>
 * Date: 2015年11月18日 <br/>
 * 方法适配器
 * 
 * @author Mr.Xiao
 * @version 1.0
 */
@Component
public class Adapter_0_page implements IMethodAdapter {
	@Autowired
	@Qualifier("baseJdbcDao")
	private IBaseJdbcDAO jdbcDao;
	@Autowired
	@Qualifier("dialects.mysql")
	private IDialect mysqlDialect;
	@Autowired
	@Qualifier("dialects.oracle")
	private IDialect oracleDialect;
	@Autowired
	@Qualifier("paramAdapters.sqlRequestParamAdapter")
	private IRequestParamAdapter requestParamAdapter;
	
	@Override
	public void doAdapter(VelocityConfigurer config, 
			Sence senceModel, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ColumnArray columns = SenceUtil.getColumns( senceModel);
		Map<String, List<Column>> mcls = getQueryAndList(columns);
		
		VelocityEngine ve = config.getVelocityEngine();
		Map param = new HashMap();
		param.put("module", senceModel.getModule());
		param.put("sence", senceModel);
		param.put("table",senceModel.getPropertys().get("table"));
		
		param.putAll(getQueryAndList(columns));
		
		String sql = VelocityEngineUtils.mergeTemplateIntoString(ve,"cn/com/ksplatform/modules/autocode/template/sql/base/select-page.vm","UTF-8",param);
		sql = FormatStyle.BASIC.getFormatter().format(sql);
		
		
		PageInfoModel pim = new PageInfoModel();
		BaseController.class.newInstance().initPage(pim, request);
		
		try {
			Map m = requestParamAdapter.doAdapter(request,null);
			String whereSql = m.get("query").toString();
			if(StringUtils.hasText(whereSql)){
				sql += (" where "+whereSql);
			}
			Object[] params = ((List)m.get("params")).toArray();
			pim = jdbcDao.queryPage(mysqlDialect,sql,pim,params);
		} catch (RuleNotFondException e) {
			pim = jdbcDao.queryPage(mysqlDialect,sql,pim);
		}
		
		Log.info(sql);
		
		ObjectMapper mapper = new ObjectMapper();
		String pageJson = mapper.writeValueAsString(pim);
		response.setContentType("application/json");
		response.getWriter().write(pageJson);
		
		/*System.out.println("查询:"+sql);
		
		param.put("columns", columns.getColumns());
		sql = VelocityEngineUtils.mergeTemplateIntoString(ve,"cn/com/ksplatform/modules/autocode/template/sql/base/insert.vm","UTF-8",param);
		sql = FormatStyle.BASIC.getFormatter().format(sql);
		System.out.println("新增:"+sql);
		
		*/
		
	}
	
	private Map<String,List<Column>> getQueryAndList(ColumnArray columnArray){
		List<Column> querys = new ArrayList<Column>();
		List<Column> lists = new ArrayList<Column>();
		List<Column> pks = new ArrayList<Column>();
		List<Column> forms = new ArrayList<Column>();
		for(Column c : columnArray.getColumns()){
			if(c.getPropertys() != null){
				if("true".equals(c.getPropertys().get("query"))){
					//查询条件
					querys.add(c);
				}
				
				if("true".equals(c.getPropertys().get("list")) && !c.getPk()){
					//列表显示
					lists.add(c);
				}
				
				if(c.getPk()){
					//主键
					pks.add(c);
				}
				
				if("true".equals(c.getPropertys().get("formShow")) && !c.getPk()){
					forms.add(c);
				}
			}
		}
		Map m = new HashMap();
		m.put("query", querys);
		m.put("list", lists);
		m.put("pk", pks);
		m.put("form", forms);
		return m;
	}
}
